package com.hk.aspect;

import com.google.common.util.concurrent.RateLimiter;
import com.hk.annotation.OpenApiRateLimiter;
import com.hk.enums.OuterErrorEnum;
import com.hk.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

@Aspect
@Component
@Slf4j
public class OpenApiRateLimiterAspect {

    private ConcurrentHashMap<String, RateLimiter> map = new ConcurrentHashMap<>();

    private RateLimiter rateLimiter;

    @Pointcut("execution(public * com.hk.controller..*.*(..))")
    public void controllerAspect(){

    }

    @Before(value = "controllerAspect()")
    public void methodBefore(JoinPoint joinpoint) {
        MethodSignature methodSignature = (MethodSignature) joinpoint.getSignature();
        Method method = methodSignature.getMethod();
        OpenApiRateLimiter openApiRateLimiter = method.getAnnotation(OpenApiRateLimiter.class);

        if (Objects.nonNull(openApiRateLimiter)) {

            String functionName = methodSignature.getName();
            double limitNum = openApiRateLimiter.limitNum();
            if (map.containsKey(functionName)) {
                rateLimiter = map.get(functionName);
            } else {
                map.put(functionName, RateLimiter.create(limitNum));
                rateLimiter = map.get(functionName);
            }

            if (!rateLimiter.tryAcquire()) {
                log.error(functionName, "，该接口已被限流！");
                throw new BizException(OuterErrorEnum.INTERFACE_ALREADY_LIMIT.getCode(), OuterErrorEnum.INTERFACE_ALREADY_LIMIT.getMsg());
            }
            return;
        }
    }



}
